package com.nwpu.intimacy.login;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.nwpu.intimacy.R;

public class ForgotPasswordActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/password";

	private EditText forgot_usernam_edit;
	private EditText forgot_email_edit;

	private Button forgot_cancel_button;
	private Button forgot_ok_button;

	private Handler loginHandler;

	private final static int USER_FORGET_SUCCESS = 0x114;
	private final static int USER_FORGET_FAIL_F = 0x115;
	private final static int USER_FORGET_FAIL_S = 0x116;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forgotpassword);

		initLayout();

		// 线程交互
		loginHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_FORGET_SUCCESS: {
					// 跳转界面 登录成功

					Toast.makeText(
							getApplicationContext(),
							"E-mail sent successfully, please check your email!",
							Toast.LENGTH_SHORT).show();

					finish();

					break;
				}
				case USER_FORGET_FAIL_F: {

					// 用户名和邮箱不匹配

					Toast.makeText(
							getApplicationContext(),
							"E-mail and username does not match, please re-enter!",
							Toast.LENGTH_SHORT).show();
					break;

				}
				case USER_FORGET_FAIL_S: {

					// 用户名不存在
					Toast.makeText(getApplicationContext(),
							"User name does not exist, please re-enter!",
							Toast.LENGTH_SHORT).show();
					break;

				}
				default:
					super.handleMessage(msg);
				}
			}

		};

	}

	private void initLayout() {

		forgot_usernam_edit = (EditText) findViewById(R.id.forgot_usernam_edit);
		forgot_email_edit = (EditText) findViewById(R.id.forgot_email_edit);
		forgot_cancel_button = (Button) findViewById(R.id.forgot_cancel_button);
		forgot_ok_button = (Button) findViewById(R.id.forgot_ok_button);

	}

	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.forgot_ok_button:// 点击确认找回密码按钮

			if (!checkInformation()) {

				return;

			}

			onChecked();

			break;
		case R.id.forgot_cancel_button:// 点击退出按钮

			finish();

			break;
		}
	}

	// 验证用户信息的完整性
	private boolean checkInformation() {

		String usernameString = forgot_usernam_edit.getText().toString();
		String emailString = forgot_email_edit.getText().toString();

		if (usernameString.equals("") || emailString.equals("")) {

			Toast.makeText(getApplicationContext(),
					"Please fill in all information!", Toast.LENGTH_SHORT)
					.show();

			return false;

		}

		if (!isEmail(emailString)) {

			return false;

		}

		return true;

	}

	// 向服务器发送找回密码请求
	public void onChecked() {

		new Thread() {

			public void run() {
				try {

					String usernameString = forgot_usernam_edit.getText()
							.toString();
					String emailString = forgot_email_edit.getText().toString();

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username", usernameString);
					jsonObject.put("email", emailString);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair(
							"forgetPassword", jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							HTTP.UTF_8));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(httpResponse
							.getEntity());

					Log.e("forgetPassword", result.toString());

					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("result").equals("success")) {

						Message msg = new Message();
						msg.what = USER_FORGET_SUCCESS;
						msg.obj = result;
						loginHandler.sendMessage(msg);

					} else if (jsonObject2.optString("result")
							.equals("noemail")) {

						Message msg = new Message();
						msg.what = USER_FORGET_FAIL_F;
						msg.obj = result;
						loginHandler.sendMessage(msg);

					} else if (jsonObject2.optString("result").equals("nouser")) {

						Message msg = new Message();
						msg.what = USER_FORGET_FAIL_S;
						msg.obj = result;
						loginHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}.start();
	}

	// 验证邮箱是否正确
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

}
